package cn.anline.www.controller;

import cn.anline.www.bean.BlogBean;
import cn.anline.www.dao.BlogDao;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/blog")
public class BlogController {

    private BlogDao blogDao;

    public BlogDao getBlogDao() {
        return blogDao;
    }

    public void setBlogDao(BlogDao blogDao) {
        this.blogDao = blogDao;
    }

    @RequestMapping("/")
    public Object _init(ModelMap modelMap){
        return this.index(modelMap);
    }
    @RequestMapping(value = "/index",method = RequestMethod.GET)
    public ModelAndView index(ModelMap modelMap){
        System.out.println("遍历博文");
        List<BlogBean> list = blogDao.findAll();
        for (BlogBean blogBean:list) {
            System.out.println("id："+blogBean.getId());
            System.out.println("所属用户id："+blogBean.getUid());
            System.out.println("标题："+blogBean.getTitle());
            System.out.println("描述："+blogBean.getDescription());
            System.out.println("内容："+blogBean.getContent());
        }
        return new ModelAndView("blog/index","list", list);
    }

    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public ModelAndView add(ModelMap modelMap){
        return new ModelAndView("blog/add",modelMap);
    }
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public ModelAndView addPost(@ModelAttribute("springweb")BlogBean blogBean, ModelMap modelMap){
        blogDao.addNew(blogBean);
        modelMap.addAttribute("title",blogBean.getTitle());
        modelMap.addAttribute("description",blogBean.getDescription());
        modelMap.addAttribute("content",blogBean.getContent());
        return new ModelAndView("blog/addres",modelMap);
    }

    @RequestMapping("/detail")
    public ModelAndView detail(ModelMap modelMap,HttpServletRequest httpServletRequest){
        int id = Integer.parseInt(httpServletRequest.getParameter("id"));
        BlogBean blogBean = new BlogBean();
        blogBean = blogDao.findById(id).get(0);
        modelMap.addAttribute("id",blogBean.getId());
        modelMap.addAttribute("title",blogBean.getTitle());
        modelMap.addAttribute("description",blogBean.getDescription());
        modelMap.addAttribute("content",blogBean.getContent());
        return new ModelAndView("blog/detail",modelMap);
    }
}
